package com.luge.model.share;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.luge.base.Base;
import com.luge.heart.R;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXMusicObject;
import com.tencent.mm.sdk.platformtools.Util;

public class WXShareAPI {
	private Context context;
	private static final int THUMB_SIZE = 150;
	private IWXAPI api;

	public WXShareAPI(Context context) {
		this.context = context;
		api = WXAPIFactory.createWXAPI(context, getAppID(context), false);
		api.registerApp(getAppID(context));
	}

	public void createDialog(final Context context, final int type,
			final String shareTitle, final String dis, final String url,
			final String imgURL) {
		Dialog alertDialog = new AlertDialog.Builder(context)
				.setTitle(context.getString(R.string.share_to_str))
				.setItems(
						context.getResources().getStringArray(R.array.share_wx),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (!api.isWXAppInstalled()) {
									unInstallWX();
								} else if (type == Share.MUSIC) {
									shareMusicWX(which, shareTitle, context
											.getString(R.string.share_content),
											url);
								} else if (type == Share.IMAGE) {
									shareImage(which, imgURL);
								}
							}
						}).create();
		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.show();
	}

	private void shareMusicWX(int which, String title, String dis, String url) {
		WXMusicObject music = new WXMusicObject();
		music.musicUrl = url;
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = music;
		msg.title = title;
		msg.description = dis;

		Bitmap thumb = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.icon);
		msg.thumbData = Util.bmpToByteArray(thumb, true);

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("music");
		req.message = msg;
		req.scene = which == 1 ? SendMessageToWX.Req.WXSceneTimeline
				: SendMessageToWX.Req.WXSceneSession;
		api.sendReq(req);
	}

	private void shareImage(final int which, final String urlStr) {
		new Thread() {
			public void run() {
				shareImgWX(which, urlStr);
			};
		}.start();
	}

	private void shareImgWX(int which, String urlStr) {
		WXImageObject imgObj = new WXImageObject();
		imgObj.imageUrl = urlStr;

		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = imgObj;
		Bitmap bitmap = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5000);
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				bitmap = BitmapFactory.decodeStream(conn.getInputStream());
			} else {
				String picPath = Base.cache_path + Constant.shareImgName;
				bitmap = BitmapFactory.decodeFile(picPath);
			}
		} catch (IOException e) {
			bitmap = null;
		}
		if (bitmap == null) {
			handler.sendEmptyMessage(0);
			return;
		}
		Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE,
				THUMB_SIZE, true);
		bitmap.recycle();
		msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("img");
		req.message = msg;
		req.scene = (which == 1) ? SendMessageToWX.Req.WXSceneTimeline
				: SendMessageToWX.Req.WXSceneSession;
		api.sendReq(req);
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	private void unInstallWX() {
		AlertDialog.Builder builder = new Builder(context)
				.setTitle(context.getString(R.string.dialog_title))
				.setMessage(context.getString(R.string.wx_not_install))
				.setPositiveButton(context.getString(R.string.download_wx),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Uri uri = Uri.parse("http://weixin.qq.com");
								Intent intent = new Intent(Intent.ACTION_VIEW,
										uri);
								context.startActivity(intent);
							}
						})
				.setNegativeButton(context.getString(R.string.clear_str),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
		builder.show();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Toast.makeText(context, R.string.load_image_fail,
					Toast.LENGTH_SHORT).show();
		}
	};

	public static String getAppID(Context context) {
		return context.getString(R.string.wx_app_id);
	}
}
